package com.haizhi.crm.biz.task.message.handler;

import com.haizhi.crm.biz.constant.MessageSourceType;
import com.haizhi.crm.biz.dao.ConcernedDao;
import com.haizhi.crm.biz.model.ConcernedDo;
import com.haizhi.crm.biz.model.MessageClientDo;
import com.haizhi.crm.biz.model.MessageUserResourceDo;
import com.haizhi.crm.biz.model.MessageUserVo;
import com.haizhi.crm.biz.task.message.model.ContextDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wangshan on 2018/5/29.
 */
@Component
public class ConcernHandler extends AbstractHandler<ContextDto> {

    @Autowired
    private ConcernedDao concernedDao;

    public static void processUserId(ContextDto data, List<Long> userList, MessageSourceType messageSourceType) {
        Map<Long, MessageUserVo> messageUserVoMap = data.getMessageUserVoMap();
        for (Long userId : userList) {
            boolean flag = messageUserVoMap.containsKey(userId);
            MessageUserResourceDo messageUserResourceDo = new MessageUserResourceDo();
            messageUserResourceDo.setMessageSourceType(messageSourceType);
            if (flag) {
                MessageUserVo messageUserVo = messageUserVoMap.get(userId);
                messageUserVo.getMessageUserResourceDoList().add(messageUserResourceDo);
            } else {
                MessageUserVo messageUserVo = new MessageUserVo();
                messageUserVo.setUserId(userId);
                messageUserVo.getMessageUserResourceDoList().add(messageUserResourceDo);
                messageUserVoMap.put(userId, messageUserVo);
            }
        }
    }

    @Override
    protected MsgResponse process(ContextDto data) {
        List<MessageClientDo> keys = data.getMessageClientDos();
        List<Long> userList = new ArrayList<>();
        for (MessageClientDo messageClientDo : keys) {
            List<ConcernedDo> concernedDos = concernedDao.findByCompanyKey(messageClientDo.getCompanyId());
            for (ConcernedDo concernedDo : concernedDos) {
                userList.add(concernedDo.getUserId());
            }
        }
        ConcernHandler.processUserId(data, userList, MessageSourceType.CONCERN);
        return MsgResponse.success();
    }
}
